$(function () {
	/******************************************初始化部分******************************************/
	const table = layui.table;
	const element = layui.element;
	// 当前的tabindex值
	let tabIndex = 0;
	// 数据请求参数
	let dataProductParams = {
		ownUserId: sessionStorage.getItem('UserId'),
		currPage: 0,
		pageSize: 10
	}
	// 选中的数据的id list
	let productIdList = []

	// 治理前表格实例
	const dataProductTable = table.render({
		elem: '#dataProductTable', 
		height: '.layui-tab-item',
		cols: [[ //表头
			{ type: 'checkbox', width: 60 },
			{ type: 'numbers', title: '序号', width: 60 }, 
			{ field: 'productName', title: '数据名称' }, 
			{
				field: 'status', title: '状态', sort: true, templet: function (d) {
					switch (d.governStatus) {
						case 0:
							return `<span>未治理</span>`
						default:
							return `<span>已治理</span>`;
					}
				}
			},
			{
				field: 'storeStatus', title: '存储管理', sort: true, templet: function (d) {
					switch (d.storeStatus) {
						case 0:
							return `<span>本平台</span>`
						case 1:
							return `<span>女娲云链</span>`
					}
				}
			}, 
			{ field: 'buyCount', title: '数据大小' }, 
			{ field: 'createTime', title: '导入时间', }, 
			{ field: 'brief', title: '备注', }, 
			{
				title: '操作', width: 350, templet: function (d) {
					switch (d.status) {
						case 0:
							return `
						<a class="layui-btn btn layui-btn-danger layui-btn-xs text-white" lay-event="edit">修改</a>
						<a class="layui-btn btn layui-btn-warm layui-btn-xs text-white" lay-event="setCilck">设置</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="evaluate">价值评估</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="detail">详情</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="delete">删除</a>
                `
						case 1:
							return `
						<a class="layui-btn btn layui-btn-danger  layui-btn-xs text-white" lay-event="edit">修改</a>
						<a class="layui-btn btn layui-btn-warm layui-btn-xs text-white" lay-event="setCilck">设置</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="evaluate">价值评估</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="delete">删除</a>
                `
						default:
							return `
						<a class="layui-btn btn layui-btn-danger  layui-btn-xs text-white" lay-event="edit">修改</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="setCilck">设置</a>
						<a class="layui-btn btn layui-btn-warm layui-btn-xs text-white" lay-event="evaluate">价值评估</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="detail">详情</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="delete">删除</a>
                `
					}

				}
			},
		]]
	})
	
	//治理后表格
	const PostGovernanceTable = table.render({
		elem: '#dataProductTable', 
		height: '.layui-tab-item', 
		cols: [[ //表头
			{ type: 'checkbox', width: 60 },
			{ type: 'numbers', title: '序号', width: 60 }, 
			{ field: 'name', title: '数据名称' }, 
			{
				field: 'storeStatus', title: '存储管理', sort: true, templet: function (d) {
					switch (d.storeStatus) {
						case 0:
							return `<span>本平台</span>`
						case 1:
							return `<span>女娲云链</span>`
					}
				}
			}, 
			{
				field: 'authorizationStatus', title: '是否需要授权', sort: true, templet: function (d) {
					switch (d.authorizationStatus) {
						case 0:
							return `<span>不需要</span>`
						case 1:
							return `<span>需要</span>`
					}
				}
			},
			{ field: 'brief', title: '备注', }, 
			{
				title: '操作', width: 300, templet: function (d) {
					switch (d.status) {
						case 0:
							return `
						<a class="layui-btn btn layui-btn-warm layui-btn-xs text-white" lay-event="setCilck">设置</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="evaluate">价值评估</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="detail">详情</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="delete">删除</a>
	            `
						case 1:
							return `
						<a class="layui-btn btn layui-btn-warm layui-btn-xs text-white" lay-event="setCilck">设置</a>
						<a class="layui-btn btn layui-btn-xs text-white"lay-event="evaluate">价值评估</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="delete">删除</a>
	            `
						default:
							return `
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="setCilck">设置</a>
						<a class="layui-btn btn layui-btn-warm layui-btn-xs text-white" lay-event="evaluate">价值评估</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="detail">详情</a>
						<a class="layui-btn btn layui-btn-xs text-white" lay-event="delete">删除</a>
	            `
					}
	
				}
			},
		]]
	})

	/******************************************事件处理部分******************************************/
	// 表格操作 修改和删除
	table.on('tool(productTable)', function (obj) {
		const data = obj.data;
		if (obj.event === 'edit') {
			window.dataProductId = data.id;
			// window.location.href = `./popupPage/productRegistryPop.html?id=${data.id}`;
			layer.open({
				type: 2,
				title: "数据修改",
				area: ['1000px', '600px'],
				content: `./popupPage/productRegistryPop.html?id=${data.id}`,
				success: function () {
					console.log('打开弹窗 里面')
				},
				end: function () {
					productgovernanceTableRender()
				}
			});
		}
		if (obj.event === 'delete') {
			let deleteUrl = '';
			let ids = data.id;

			if (tabIndex === 0) { // 治理前数据
				deleteUrl = window.Http + `/dataProduct/${ids}`;
			} else if (tabIndex === 1) { // 治理后数据
				deleteUrl = window.Http + `/property/datarawGovernLog/${ids}`;
			}

			$.ajax({
				timeout: 30000,
				url: deleteUrl,
				type: 'DELETE',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				success: function (res) {
					if (res.code === 200) {
						layer.msg('删除成功');
					} else {
						layer.msg(res.msg);
					}
					productgovernanceTableRender(); // 重新渲染表格
				},
				error: function (xhr, status, error) {
					layer.msg('删除失败，请稍后再试');
				}
			});
		}

		else if (obj.event === 'evaluate') {//评估
			$.ajax({
				timeout: 30000,
				url: window.Http + "/property/data/evaluate",
				type: 'POST',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data: JSON.stringify({
					id: data.id,
					type: tabIndex
				}),
				contentType: 'application/json;charset=utf-8',
				success: function (res) {
					if (res.code === 200) {
						layer.msg('评估');
						productgovernanceTableRender()
					} else {
						layer.msg(res.msg)
					}
				}
			})
		} else if (obj.event === 'detail') { // 详情 只有上架之后才有详情
			window.dataProductId = data.id;
			let detailUrl = '';

			if (tabIndex === 1) { // tabIndex = 1 表示治理后
				detailUrl = `./popupPage/datarawGovernPop.html?id=${data.id}`;
			} else { // tabIndex = 0 表示治理前
				detailUrl = `./popupPage/prodetailPop.html?id=${data.id}`;
			}

			layer.open({
				type: 2,
				title: "数据详情",
				area: ['1000px', '600px'],
				content: detailUrl,
				success: function () {
					console.log('打开弹窗 里面')
				},
				end: function () {
					productgovernanceTableRender()
				}
			});
		} else if (obj.event === 'test') {//测试
			let testLoad = layer.load(1);
			$.ajax({
				timeout: 30000,
				url: window.Http + '/dataProduct/execute',
				type: 'POST',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				contentType: 'application/json',
				data: JSON.stringify({
					type: 1,
					productId: data.id
				}),
				success: function (res) {
					if (res.code === 200 && res.data.RetCode === 0) {
						console.log('测试', res)
						layer.msg('测试通过')
						layer.close(testLoad);
					} else {
						layer.msg(res.data?.ErrorMsg || res.msg || '测试失败')
						layer.close(testLoad);
					}
				},
				error:function () {
					layer.close(testLoad);
					layer.msg('测试请求失败')
				}
			})
		}else if (obj.event === 'setCilck') { // 设置
			window.dataProductId = data.id;

			let detailUrl;
			if (tabIndex === 1) { // tabIndex = 1 表示治理后
				detailUrl = `./popupPage/datarawSetPop.html?id=${data.id}`;
			} else { // tabIndex = 0 表示治理前
				detailUrl = `./popupPage/productSetPop.html?id=${data.id}`;
			}

			layer.open({
				type: 2,
				title: "数据设置",
				area: ['800px', '300px'],
				content: detailUrl,
				success: function () {
					console.log('打开弹窗 里面');
				},
				end: function () {
					productgovernanceTableRender();
				}
			});
		}
	})
	// 表格复选框选中事件
	table.on('checkbox(productTable)', function (obj) {
		if (obj.type === 'all' && obj.checked) {
			productIdList = table.cache['dataProductTable'].map(item => item.id);
			// console.log('ids', ids)
		} else if (obj.type === 'one' && obj.checked) {//选中
			productIdList.push(obj.data.id)
			console.log('sourceIdList', productIdList)
		} else if (obj.type === 'all' && !obj.checked) {//取消选中
			productIdList = []
		} else if (obj.type === 'one' && !obj.checked) {//取消选中
			// 查找值的索引
			const index = productIdList.indexOf(obj.data.id);
			if (index !== -1) {
				productIdList.splice(index, 1);
			}
		}
	});

	// 提交治理数据
	$("#submitDataProductAll").on('click', function () {
		if (tabIndex === 0) {
			if (productIdList.length > 0) {
				const requestData = {
					productIds: productIdList,
					dataGovernId: 0
				};
				$.ajax({
					timeout: 30000,
					url: window.Http + '/property/data/govern',
					type: 'POST',
					headers: {
						'Authorization': "Bearer " + sessionStorage.getItem('Token'),
						'Content-Type': 'application/json'
					},
					data: JSON.stringify(requestData),
					success: function (res) {
						if (res.code === 200) {
							layer.msg('提交成功');
						} else {
							layer.msg(res.msg);
						}
					},
					error: function (xhr, status, error) {
						layer.msg('请求失败，请稍后再试');
					}
				});
			} else {
				layer.msg('当前未选中数据');
			}
		} else {
			layer.msg('仅原始数据可以进行数据治理！');
		}
	});



	// 批量删除数据按钮
	// $('#deleteDataProductAll').on('click', function () {
	// 	if (productIdList.length > 0) {
	// 		$.ajax({
	// 			timeout: 30000,
	// 			url: window.Http + '/dataProduct/' + productIdList.join(','),
	// 			type: 'DELETE',
	// 			headers: {
	// 				'Authorization': "Bearer " + sessionStorage.getItem('Token')
	// 			},
	// 			success: function (res) {
	// 				if (res.code === 200) {
	// 					layer.msg('删除成功')
	// 					productIdList = []
	// 					productgovernanceTableRender()
	// 				} else {
	// 					layer.msg(res.msg)
	// 				}
	// 			}
	// 		})
	// 	} else {
	// 		layer.msg('当前未选中数据')
	// 	}
	// })
	// 选项卡切换 0-治理前，1-治理后
	element.on('tab(productTab)', function (data) {
		tabIndex = data.index;
		productgovernanceTableRender();
		productIdList = [];
	});
	// 注册部分
	// 数据注册
	$("#productRegistration").click(function () {
		window.dataProductId = null;
		layer.open({
			type: 2,
			title: "数据注册",
			area: ['1000px', '600px'],
			content: './popupPage/productRegistryPop.html',
			success: function () {
				console.log('打开弹窗 外面')
			},
			end: function () {
				element.tabChange('productTab','online');
				productgovernanceTableRender()
			}
		});
		// window.location.href = `./popupPage/productRegistryPop.html`;
	})
	/******************************************功能函数部分******************************************/
	/**
	 * @Date：2023-09-23, 周六, 15:53
	 * @description: 请求列表 并渲染表格
	 * @param   {Object} params 请求参数 
	 * @return {Promise} 请求的结果
	 */
	//治理前数据请求
	function PreGovernanceData(params) {
		return new Promise((function (resolve, reject) {
			$.ajax({
				timeout: 30000,
				url: window.Http + "/dataProduct/list",
				type: 'GET',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data: params,
				success: function (res) {
					if (res.code === 200) {
						console.log(res)
						resolve(res)
					} else {
						layer.msg(res.msg)
						reject(new Error("请求失败")); // 失败时将错误传递给调用者
					}
				}
			})
		}))
	}
	//治理后的数据请求
	function PostGovernanceData(params){
		return new Promise((function (resolve, reject) {
			$.ajax({
				timeout: 30000,
				url: window.Http + "/property/datarawGovernLog/list",
				type: 'GET',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data: params,
				success: function (res) {
					if (res.code === 200) {
						resolve(res)
						console.log(res);
					} else {
						layer.msg(res.msg)
						reject(new Error("请求失败")); // 失败时将错误传递给调用者
					}
				}
			})
		}))
	}  
	/**
	 * @description:函数描述 渲染表格和分页
	 * @return 返回值 无
	 */
	//治理前
	function productgovernanceTableRender() {
		if(tabIndex == 0){//治理前
			PreGovernanceData(dataProductParams).then(res => {
				// 重新加载数据表格
				dataProductTable.reload({ data: res.rows });
				// 渲染分页插件
				layui.laypage.render({
					elem: 'dataProductTadatablePage', // 分页插件的 DOM 元素 ID
					count: res.total, // 数据总数，从服务端获取
					limit: 10, // 每页显示条数
					groups: 5, // 连续显示分页数
					jump: function (obj, first) {
						if (!first) {
							// 不是首次加载时才执行跳转逻辑
							dataProductParams.currPage = obj.curr; // 更新当前页数
							PreGovernanceData(dataProductParams).then(res => {
								// 重新加载数据
								dataProductTable.reload({ data: res.rows });
							});
						}
					}
				});
			}).catch(err => {
				console.error('获取数据失败:', err);
				layer.msg('获取数据失败，请稍后重试');
			});

		}else{//治理后
			PostGovernanceData(dataProductParams).then(res => {
				// 重新加载数据表格
				PostGovernanceTable.reload({ data: res.rows });
				// 渲染分页插件
				layui.laypage.render({
					elem: 'dataProductTadatablePage', // 分页插件的 DOM 元素 ID
					count: res.total, // 数据总数，从服务端获取
					limit: 10, // 每页显示条数
					groups: 5, // 连续显示分页数
					jump: function (obj, first) {
						if (!first) {
							// 不是首次加载时才执行跳转逻辑
							dataProductParams.currPage = obj.curr; // 更新当前页数
							PostGovernanceData(dataProductParams).then(res => {
								// 重新加载数据
								PostGovernanceTable.reload({ data: res.rows });
							});
						}
					}
				});
			}).catch(err => {
				console.error('获取数据失败:', err);
				layer.msg('获取数据失败，请稍后重试');
			});

		}
		
	}
	productgovernanceTableRender()

})
